// 设置异步延迟间隔
import {ORDERING_GET_USER_INFO} from "@/assets/const/api";
import {HttpUtil} from "@/config/HttpUtil";
import store from '@/store/index.js';
export function readFile(file) {
    return new Promise((resolve) => {
        let reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = (e) => {
            resolve(e.target.result);
        };
    });
}

export function excelSerialToDateString(excelSerial) {
    // Excel日期的基准是1900年1月0日（即1899年12月31日）
    const baseDate = new Date(1899, 11, 30);
    // 将Excel日期序列号转换为JavaScript日期对象，并加上一天的偏差
    const jsDate = new Date(baseDate.getTime() + (excelSerial + 1) * 24 * 60 * 60 * 1000);

    const year = jsDate.getFullYear();
    const month = String(jsDate.getMonth() + 1).padStart(2, '0'); // getMonth() 返回值范围是0-11，需要加1
    const day = String(jsDate.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}
export function getUserInfo() {
    return new Promise((resolve, reject) => {
        HttpUtil.get(ORDERING_GET_USER_INFO).then(res => {
            let info = res.data || {};
            store.commit('setUserInfo', info);
            resolve();
        }).catch((err) => {
            reject(err);
        });
    });
}
export function dlParseJSON(jsonString) {
    function skipWhitespace() {
        while (jsonString[index] === ' ' || jsonString[index] === '\n' || jsonString[index] === '\t' || jsonString[index] === '\r') {
            index++;
        }
    }

    function parseValue() {
        skipWhitespace();
        const char = jsonString[index];
        if (char === '{') return parseObject();
        if (char === '[') return parseArray();
        if (char === '"') return parseString();
        if (char === 't' || char === 'f') return parseBoolean();
        if (char === 'n') return parseNull();
        if (char === '-' || (char >= '0' && char <= '9')) return parseNumberOrBigInt();
        throw new SyntaxError(`Unexpected token ${char} at position ${index}`);
    }

    function parseObject() {
        const obj = {};
        index++;
        skipWhitespace();
        while (jsonString[index] !== '}') {
            const key = parseString();
            skipWhitespace();
            if (jsonString[index] !== ':') throw new SyntaxError(`Expected ':' at position ${index}`);
            index++;
            const value = parseValue();
            obj[key] = value;
            skipWhitespace();
            if (jsonString[index] === '}') break;
            if (jsonString[index] !== ',') throw new SyntaxError(`Expected ',' at position ${index}`);
            index++;
            skipWhitespace();
        }
        index++;
        return obj;
    }

    function parseArray() {
        const arr = [];
        index++;
        skipWhitespace();
        while (jsonString[index] !== ']') {
            const value = parseValue();
            arr.push(value);
            skipWhitespace();
            if (jsonString[index] === ']') break;
            if (jsonString[index] !== ',') throw new SyntaxError(`Expected ',' at position ${index}`);
            index++;
            skipWhitespace();
        }
        index++;
        return arr;
    }

    function parseString() {
        let str = '';
        index++;
        while (jsonString[index] !== '"') {
            if (jsonString[index] === '\\') {
                index++;
                const escapeChar = jsonString[index];
                switch (escapeChar) {
                    case '"': str += '"'; break;
                    case '\\': str += '\\'; break;
                    case '/': str += '/'; break;
                    case 'b': str += '\b'; break;
                    case 'f': str += '\f'; break;
                    case 'n': str += '\n'; break;
                    case 'r': str += '\r'; break;
                    case 't': str += '\t'; break;
                    case 'u':
                        const hex = jsonString.slice(index + 1, index + 5);
                        if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw new SyntaxError(`Invalid Unicode escape sequence at position ${index}`);
                        str += String.fromCharCode(parseInt(hex, 16));
                        index += 4;
                        break;
                    default: throw new SyntaxError(`Invalid escape character \\${escapeChar} at position ${index}`);
                }
            } else {
                str += jsonString[index];
            }
            index++;
        }
        index++;
        return str;
    }

    function parseNumberOrBigInt() {
        const numStr = [];
        if (jsonString[index] === '-') {
            numStr.push('-');
            index++;
        }
        while (jsonString[index] >= '0' && jsonString[index] <= '9') {
            numStr.push(jsonString[index]);
            index++;
        }
        if (jsonString[index] !== '.' && (jsonString[index] !== 'e' && jsonString[index] !== 'E')) {
            const bigIntStr = numStr.join('');
            if (bigIntStr.length > 15) {
                // 将大数值转换为字符串以避免精度问题
                return bigIntStr;
            } else {
                return parseInt(bigIntStr, 10);
            }
        }
        if (jsonString[index] === '.') {
            numStr.push('.');
            index++;
            while (jsonString[index] >= '0' && jsonString[index] <= '9') {
                numStr.push(jsonString[index]);
                index++;
            }
        }
        if (jsonString[index] === 'e' || jsonString[index] === 'E') {
            numStr.push('e');
            index++;
            if (jsonString[index] === '+' || jsonString[index] === '-') {
                numStr.push(jsonString[index]);
                index++;
            }
            while (jsonString[index] >= '0' && jsonString[index] <= '9') {
                numStr.push(jsonString[index]);
                index++;
            }
        }
        return parseFloat(numStr.join(''));
    }

    function parseBoolean() {
        if (jsonString.slice(index, index + 4) === 'true') {
            index += 4;
            return true;
        }
        if (jsonString.slice(index, index + 5) === 'false') {
            index += 5;
            return false;
        }
        throw new SyntaxError(`Unexpected token at position ${index}`);
    }

    function parseNull() {
        if (jsonString.slice(index, index + 4) === 'null') {
            index += 4;
            return null;
        }
        throw new SyntaxError(`Unexpected token at position ${index}`);
    }

    let index = 0;
    const result = parseValue();
    skipWhitespace();
    if (index !== jsonString.length) {
        throw new SyntaxError('Unexpected end of JSON input');
    }
    return result;
}